package top.yqingyu.trans$client.sc.command.impl;

import lombok.extern.slf4j.Slf4j;
import top.yqingyu.common.utils.IoUtil;
import top.yqingyu.common.utils.ThreadUtil;
import top.yqingyu.qymsg.MsgHelper;
import top.yqingyu.qymsg.QyMsg;
import top.yqingyu.trans$client.common.TransSocket;
import top.yqingyu.trans$client.cs.command.Command;
import top.yqingyu.trans$client.main.TransClient;

import java.net.Socket;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.transclient.sc.command.impl.Forward
 * @description
 * @createTime 2022年07月23日 18:00:00
 */
@Slf4j
public class ForwardCommand extends Command {

    private static final String commandRegx = "^(forward).*$";
    private static final ThreadPoolExecutor IO_POOL = ThreadUtil.createQyFixedThreadPool(20, "trans", null);

    @Override
    public void deal(QyMsg msg, TransClient client) throws Exception {
        QyMsg clone = client.clientConf.NORMAL_MSG.clone();
        clone.putMsgData("key", "fwd");


        String port = MsgHelper.gainMsgValue(msg, "port");
        Socket transSocket = TransSocket.getTransSocket(client, client.clientConf.HOST, client.clientConf.PORT3);

        if (transSocket != null && transSocket.isConnected()) {

            Socket proxy = null;

            try {
                proxy = new Socket("127.0.0.1", Integer.parseInt(port));
                IoUtil.transSocket(transSocket, proxy, IO_POOL, 1024);
            } catch (Exception e) {
                assert proxy != null;
                proxy.close();
                transSocket.close();
                log.error("forward 异常", e);
            }

        }
    }
}
